{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Copyright 2014 Brett Slatkin, Pearson Education Inc.\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "# Preamble to mimick book environment\n",
    "import logging\n",
    "from pprint import pprint\n",
    "from sys import stdout as STDOUT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Example 1\n",
    "class ToDictMixin(object):\n",
    "    def to_dict(self):\n",
    "        return self._traverse_dict(self.__dict__)\n",
    "\n",
    "# Example 2\n",
    "    def _traverse_dict(self, instance_dict):\n",
    "        output = {}\n",
    "        for key, value in instance_dict.items():\n",
    "            output[key] = self._traverse(key, value)\n",
    "        return output\n",
    "\n",
    "    def _traverse(self, key, value):\n",
    "        if isinstance(value, ToDictMixin):\n",
    "            return value.to_dict()\n",
    "        elif isinstance(value, dict):\n",
    "            return self._traverse_dict(value)\n",
    "        elif isinstance(value, list):\n",
    "            return [self._traverse(key, i) for i in value]\n",
    "        elif hasattr(value, '__dict__'):\n",
    "            return self._traverse_dict(value.__dict__)\n",
    "        else:\n",
    "            return value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Example 3\n",
    "class BinaryTree(ToDictMixin):\n",
    "    def __init__(self, value, left=None, right=None):\n",
    "        self.value = value\n",
    "        self.left = left\n",
    "        self.right = right"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'left': {'left': None,\n",
      "          'right': {'left': None, 'right': None, 'value': 9},\n",
      "          'value': 7},\n",
      " 'right': {'left': {'left': None, 'right': None, 'value': 11},\n",
      "           'right': None,\n",
      "           'value': 13},\n",
      " 'value': 10}\n"
     ]
    }
   ],
   "source": [
    "# Example 4\n",
    "tree = BinaryTree(10,\n",
    "    left=BinaryTree(7, right=BinaryTree(9)),\n",
    "    right=BinaryTree(13, left=BinaryTree(11)))\n",
    "orig_print = print\n",
    "print = pprint\n",
    "print(tree.to_dict())\n",
    "print = orig_print"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Example 5\n",
    "class BinaryTreeWithParent(BinaryTree):\n",
    "    def __init__(self, value, left=None,\n",
    "                 right=None, parent=None):\n",
    "        super().__init__(value, left=left, right=right)\n",
    "        self.parent = parent\n",
    "\n",
    "# Example 6\n",
    "    def _traverse(self, key, value):\n",
    "        if (isinstance(value, BinaryTreeWithParent) and\n",
    "                key == 'parent'):\n",
    "            return value.value  # Prevent cycles\n",
    "        else:\n",
    "            return super()._traverse(key, value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'left': {'left': None,\n",
      "          'parent': 10,\n",
      "          'right': {'left': None, 'parent': 7, 'right': None, 'value': 9},\n",
      "          'value': 7},\n",
      " 'parent': None,\n",
      " 'right': None,\n",
      " 'value': 10}\n"
     ]
    }
   ],
   "source": [
    "# Example 7\n",
    "root = BinaryTreeWithParent(10)\n",
    "root.left = BinaryTreeWithParent(7, parent=root)\n",
    "root.left.right = BinaryTreeWithParent(9, parent=root.left)\n",
    "orig_print = print\n",
    "print = pprint\n",
    "print(root.to_dict())\n",
    "print = orig_print"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'foobar',\n",
      " 'tree_with_parent': {'left': None, 'parent': 7, 'right': None, 'value': 9}}\n"
     ]
    }
   ],
   "source": [
    "# Example 8\n",
    "class NamedSubTree(ToDictMixin):\n",
    "    def __init__(self, name, tree_with_parent):\n",
    "        self.name = name\n",
    "        self.tree_with_parent = tree_with_parent\n",
    "\n",
    "my_tree = NamedSubTree('foobar', root.left.right)\n",
    "orig_print = print\n",
    "print = pprint\n",
    "print(my_tree.to_dict())  # No infinite loop\n",
    "print = orig_print"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 9\n",
    "import json\n",
    "\n",
    "class JsonMixin(object):\n",
    "    @classmethod\n",
    "    def from_json(cls, data):\n",
    "        kwargs = json.loads(data)\n",
    "        return cls(**kwargs)\n",
    "\n",
    "    def to_json(self):\n",
    "        return json.dumps(self.to_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 10\n",
    "class DatacenterRack(ToDictMixin, JsonMixin):\n",
    "    def __init__(self, switch=None, machines=None):\n",
    "        self.switch = Switch(**switch)\n",
    "        self.machines = [\n",
    "            Machine(**kwargs) for kwargs in machines]\n",
    "\n",
    "class Switch(ToDictMixin, JsonMixin):\n",
    "    def __init__(self, ports=None, speed=None):\n",
    "        self.ports = ports\n",
    "        self.speed = speed\n",
    "\n",
    "class Machine(ToDictMixin, JsonMixin):\n",
    "    def __init__(self, cores=None, ram=None, disk=None):\n",
    "        self.cores = cores\n",
    "        self.ram = ram\n",
    "        self.disk = disk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Example 11\n",
    "serialized = \"\"\"{\n",
    "    \"switch\": {\"ports\": 5, \"speed\": 1e9},\n",
    "    \"machines\": [\n",
    "        {\"cores\": 8, \"ram\": 32e9, \"disk\": 5e12},\n",
    "        {\"cores\": 4, \"ram\": 16e9, \"disk\": 1e12},\n",
    "        {\"cores\": 2, \"ram\": 4e9, \"disk\": 500e9}\n",
    "    ]\n",
    "}\"\"\"\n",
    "\n",
    "deserialized = DatacenterRack.from_json(serialized)\n",
    "roundtrip = deserialized.to_json()\n",
    "assert json.loads(serialized) == json.loads(roundtrip)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
